package bar.dark.lee.manager.card;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;

import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.manager.money.BankMoneyActivitiy;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CreditCardActivity extends SuperActivity
	implements OnClickListener
{
	
/////////////////////////////////////////////////////////////////
///////////////////		위젯 멤버 변수		/////////////////////
/////////////////////////////////////////////////////////////////

	protected static final String CREDITCARD_DATA = "creditcard_data";
	private Button mBtnAdd;
	private ListView mListCreditCard;
	private View buttonView;

/////////////////////////////////////////////////////////////////
///////////////////		일반 멤버 변수		/////////////////////
/////////////////////////////////////////////////////////////////

	private ArrayList<CreditCardData> mArrayCreditCard;
	private ArrayAdapter<CreditCardData> mAdapterCreditCard; 

	// 그 외
	private DBSQLite dbSql;
	
	private View resultView;
	
/////////////////////////////////////////////////////////////////
///////////////////		오버라이딩 메소드		/////////////////////
/////////////////////////////////////////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_creditcard_activity);
		
		dbSql = DBSQLite.getInstance(this);
		
		if (getIntent().getBooleanExtra(BankMoneyActivitiy.LINK_CARD, false))
		{
			setTitle("연결카드 목록");
			setGoneTipButton();
		}
		else
		{
			setGoneTitle();
		}
		
		initWidget();
		initListener();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(0);
	}
	
	private void setData()
	{
		getCreditCardData();
		
		for (int i=0; i<mArrayCreditCard.size(); i++) 
		{
			getBankBookData(i, mArrayCreditCard.get(i).getBanklink());
		}
		
		Calendar cal = Calendar.getInstance();
		toYear = cal.get(Calendar.YEAR);
    	toMonth = cal.get(Calendar.MONTH);
    	toDay = cal.get(Calendar.DAY_OF_MONTH);
    	
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		/** 시작일로 카드대금 가져올지 기간으로 가져올지 플래그 */
		int postCheck = pref.getInt(BDConstents.MONTH_POSTMONEY_SETTING, 0);
		int fanOkNoFlag = pref.getInt(BDConstents.FAN_SETTING_OK_NO, 0);
		
		String fanSql = "";
		String sql = "";

		// 달 시작일 가져온다
    	int startDate = Integer.parseInt(pref.getString(BDConstents.START_DATE, "1"));
    	
    	String firstDate = "";
    	String lastDate = "";
    	
    	// 시작일이 1일이면 원래대로
    	if (startDate == 1) 
    	{
    		firstDate = BDUtil.getDateDB(toYear, toMonth+1, 1);
    		lastDate = BDUtil.getDateDB(toYear, toMonth+1, 31); 
    	}
    	else
    	{
    		if (toMonth+1 == 1)
    		{
    			// 1월이면 
    			if (toDay < startDate)
    			{
    				// 저번달에 낑겨있으면
    				// 1월이면 작년 12월 시작일부터 올해 이번달 시작일전날까지
        			// 이달의 지출
    				firstDate = BDUtil.getDateDB(toYear-1, 12, startDate);
    				lastDate = BDUtil.getDateDB(toYear, 1, startDate-1);
    			}
    			else
    			{
    				// 새달이 시작됐으면
    				// 1월이면 1월 시작일부터 2월 시작일전날까지
        			// 이달의 지출
    				firstDate = BDUtil.getDateDB(toYear, 1, startDate);
    				lastDate = BDUtil.getDateDB(toYear, 2, startDate-1);
    			}    			
    		}
    		else if (toMonth+1 == 12)
    		{
    			// 12월이면 
    			if (toDay < startDate)
    			{
    				// 저번달에 낑겨있으면
    				// 올해 11월 시작일부터 올해 12월 시작일전날까지
        			// 이달의 지출
    				firstDate = BDUtil.getDateDB(toYear, 11, startDate);
    				lastDate = BDUtil.getDateDB(toYear, 12, startDate-1);
    			}
    			else
    			{
    				// 새달이 시작됐으면
    				// 작년 12월 시작일부터 1월 시작일전날까지
        			// 이달의 지출
    				firstDate = BDUtil.getDateDB(toYear, 12, startDate);
    				lastDate = BDUtil.getDateDB(toYear+1, 1, startDate-1);
    			}
    		}
    		else
    		{
    			// 1월이 아니면
    			if (toDay < startDate)
    			{
    				// 전달에 낑겨있으면
    				// 이달의 지출
    				firstDate = BDUtil.getDateDB(toYear, toMonth, startDate);
    				lastDate = BDUtil.getDateDB(toYear, toMonth+1, startDate-1);
    			}
    			else
    			{
    				// 새달이 시작됐으면
    				// 이달의 지출
    				firstDate = BDUtil.getDateDB(toYear, toMonth+1, startDate);
    				lastDate = BDUtil.getDateDB(toYear, toMonth+2, startDate-1);
    			}
    		}
    	}
    	
    	// 부채 포함여부에 따른 쿼리
    	if (fanOkNoFlag != 0)
		{
    		fanSql =  " and type not in ( " + BDConstents.FAN_TYPE + " )";
		}
		
		if (postCheck == 0)
		{
			for (int i = 0; i < mArrayCreditCard.size(); i++)
			{
				CreditCardData data = mArrayCreditCard.get(i);
				
				sql = "SELECT postmoney FROM in_out WHERE date >= " 
						+ firstDate + " and date <= " 
						+ lastDate + fanSql + " and moneykind = '" + BDUtil.getApostrophe(data.getName()) + "';";
				
				dbSql.selectMapTile(this, sql, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int count = c.getCount();
						
						int columIndex = c.getColumnIndex("postmoney");
						c.moveToFirst();
//						int money = 0;
						postTermMoney = BigDecimal.ZERO;
						
						for (int i = 0; i < count; i++)
						{
//							money = money + Integer.parseInt(c.getString(columIndex));
							postTermMoney = postTermMoney.add(new BigDecimal(c.getString(columIndex)));
							c.moveToNext();
						}
					}
				});
				
				mArrayCreditCard.get(i).setOutMoney(postTermMoney.toString());
			}
		}
		else
		{
			setPostMoneyTerm();
		}
	}

	@Override
	public void onClick(View v) {
		if (v == mBtnAdd) {
			Intent intent = new Intent(this, CreditCardAddActivity.class);
			startActivityForResult(intent, 0);
		}
	}
	
	/**
	* 위젯 초기화
	*/
	private void initWidget() 
	{
		mBtnAdd = (Button)findViewById(R.id.SETTING_CREDITCARD_btnAdd);
		mListCreditCard = (ListView)findViewById(R.id.SETTING_CREDITCARD_list);
		buttonView = findViewById(R.id.creditCardButtonView);
		
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
	}
	
	/**
	* 리스너 초기화
	*/
	private void initListener() 
	{
		mBtnAdd.setOnClickListener(this);
	}

	/**
	 * 신용카드 데이터 가져온다
	 */
	private void getCreditCardData() 
	{
		mArrayCreditCard = new ArrayList<CreditCardData>();
		
		String query = "";
		
		// 통장삭제에서 왔을경우 그 통장에 연결된 카드만 보여준다.
		if (getIntent().getBooleanExtra(BankMoneyActivitiy.LINK_CARD, false))
		{
//			query = "SELECT id, name, banklink, outmoney, outdate FROM credit_card WHERE banklink = " 
//				+ getIntent().getStringExtra(BankMoneyActivitiy.CARD_ID) + ";";
			
			query = "SELECT id, name, banklink, outmoney, outdate, count FROM ( " +
					"SELECT b.id id, b.name name, b.banklink banklink, b.outmoney outmoney, b.outdate outdate, " +
					"FROM credit_card b, creditcard_detail d " +
					"d.count count WHERE b.id = d.linkid and d.count > 0 and " +
					"b.banklink = " +	getIntent().getStringExtra(BankMoneyActivitiy.CARD_ID) + " ORDER BY count) " +
					"UNION ALL " +
					"SELECT id, name, banklink, outmoney, outdate, count FROM ( " +
					"SELECT b.id id, b.name name, b.banklink banklink, b.outmoney outmoney, b.outdate outdate, " +
					"d.count count FROM credit_card b, creditcard_detail d " +
					"WHERE b.id = d.linkid and d.count < 1 and " +
					"b.banklink = " +	getIntent().getStringExtra(BankMoneyActivitiy.CARD_ID) + " ORDER BY count);";
			
			buttonView.setVisibility(View.GONE);
		}
		else
		{
//			query = "SELECT id, name, banklink, outmoney, outdate FROM credit_card;";
			
			query = "SELECT id, name, banklink, outmoney, outdate, count FROM ( " +
					"SELECT b.id id, b.name name, b.banklink banklink, b.outmoney outmoney, b.outdate outdate, " +
					"d.count count FROM credit_card b, creditcard_detail d " +
					"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
					"UNION ALL " +
					"SELECT id, name, banklink, outmoney, outdate, count FROM ( " +
					"SELECT b.id id, b.name name, b.banklink banklink, b.outmoney outmoney, b.outdate outdate, " +
					"d.count count FROM credit_card b, creditcard_detail d " +
					"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);";
			
			buttonView.setVisibility(View.VISIBLE);
		}
		
		dbSql.selectMapTile(this, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				c.moveToFirst();
				
				int idIndex = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				int banklinkIndex = c.getColumnIndex("banklink");
				int outmoneyIndex = c.getColumnIndex("outmoney");
				int outdateIndex = c.getColumnIndex("outdate");
				int countIndex = c.getColumnIndex("count");
				
				for (int i = 0; i < count; i++)
				{
					CreditCardData data = new CreditCardData();
					data.setId(c.getInt(idIndex) + "");
					data.setName(c.getString(nameIndex));
					data.setBanklink(c.getInt(banklinkIndex)+"");
					data.setOutMoney(c.getString(outmoneyIndex)+"");
					data.setOutDate(c.getInt(outdateIndex) + "");
					data.setOrder(c.getString(countIndex));
					mArrayCreditCard.add(data);
					c.moveToNext();
				}
			}
		});
	}
	
	/**
	 * 통장 데이터 가져온다
	 */
	private void getBankBookData(final int index, String id) {
		
		dbSql.selectMapTile(this, "SELECT money, name FROM bankbook" +
				" WHERE id = " + id + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				c.moveToFirst();
				int moneyIndex = c.getColumnIndex("money");
				int nameIndex = c.getColumnIndex("name");
				mArrayCreditCard.get(index).setMoney(c.getString(moneyIndex));
				mArrayCreditCard.get(index).setLinkName(c.getString(nameIndex));
			}
		});
	}

	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			CreditCardData data = mArrayCreditCard.get(position);
			
			Intent intent = new Intent(CreditCardActivity.this, CreditCardUpdateActivity.class);
			intent.putExtra(CREDITCARD_DATA, data);
			startActivityForResult(intent, 0);
		}
	};
	
	private BigDecimal postTermMoney = BigDecimal.ZERO;
	private ArrayList<CreditCardResultDateData> creditResultList = null;
	
	private int toYear;
	private int toMonth;
	private int toDay;
	
	/**
	 * 카드 사용 일자로 카드 사용 금액을 가져온다.
	 */
	private void setPostMoneyTerm()
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		
		int fanOkNoFlag = pref.getInt(BDConstents.FAN_SETTING_OK_NO, 0);
		
		creditResultList = new ArrayList<CreditCardResultDateData>();
		
		dbSql.selectMapTile(this, "SELECT * FROM credit_card_result_date;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int autoynIdx = c.getColumnIndex("autoyn");
				int startdateIdx = c.getColumnIndex("startdate");
				int enddateIdx = c.getColumnIndex("enddate");
				int resultdateIdx = c.getColumnIndex("resultdate");
				int resultflagIdx = c.getColumnIndex("resultflag");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					CreditCardResultDateData creditResultData = new CreditCardResultDateData();
					
					creditResultData.setId(c.getInt(idIdx) + "");
					creditResultData.setName(c.getString(nameIdx));
					creditResultData.setAutoyn(c.getInt(autoynIdx) + "");
					creditResultData.setStartdate(c.getInt(startdateIdx) + "");
					creditResultData.setEnddate(c.getInt(enddateIdx) + "");
					creditResultData.setResultdate(c.getInt(resultdateIdx) + "");
					creditResultData.setResultflag(c.getInt(resultflagIdx) + "");
					creditResultData.setLinkid(c.getInt(linkidIdx) + "");
					
					creditResultList.add(creditResultData);
					
					c.moveToNext();
				}
			}
		});
		
		for (int i = 0; i < creditResultList.size(); i++)
		{
			CreditCardResultDateData data = creditResultList.get(i);
			
			postTermMoney = BigDecimal.ZERO;
			
			String moneykind = data.getName();
			
			int startDay = Integer.parseInt(data.getStartdate());
			int endDay = Integer.parseInt(data.getEnddate());
			
			String firstDate = "";
			String lastDate = "";
			
			if (toDay >= startDay)
			{
				if (startDay == 1)
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth+1, startDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth+1, endDay);
				}
				else if (toMonth == 11)
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth+1, startDay);
					lastDate = BDUtil.getDateDB(toYear+1, 1, endDay);
				}
				else
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth+1, startDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth+2, endDay);
				}
			}
			else
			{
				if (startDay == 1)
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth, endDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth, endDay);
				}
				else if (toMonth == 0)
				{
					firstDate = BDUtil.getDateDB(toYear-1, 12, startDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth+1, endDay);
				}
				else
				{
					firstDate = BDUtil.getDateDB(toYear, toMonth, startDay);
					lastDate = BDUtil.getDateDB(toYear, toMonth+1, endDay);
				}
			}
			
			if (firstDate.equals(""))
			{
				continue;
			}
			
			String fanSql = "";
	    	
	    	// 부채 포함여부에 따른 쿼리
	    	if (fanOkNoFlag != 0)
			{
	    		fanSql =  " and type not in ( " + BDConstents.FAN_TYPE + " )";
			}
			
			String sql = "SELECT postmoney FROM in_out WHERE date >= " 
					+ firstDate + " and date <= " 
					+ lastDate + " and moneykind = '" 
					+ BDUtil.getApostrophe(moneykind) + "'" + fanSql + ";";
			
			dbSql.selectMapTile(this, sql, new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int count = c.getCount();
					
					int columIndex = c.getColumnIndex("postmoney");
					c.moveToFirst();
//					int money = 0;
					
					for (int i = 0; i < count; i++)
					{
//						money = money + Integer.parseInt(c.getString(columIndex));
						postTermMoney = postTermMoney.add(new BigDecimal(c.getString(columIndex)));
						c.moveToNext();
					}
				}
			});
			
			mArrayCreditCard.get(i).setOutMoney(postTermMoney.toString());
		}
	}


/////////////////////////////////////////////////////////////////
///////////////////			내부 클래스		/////////////////////
/////////////////////////////////////////////////////////////////

	/**
	 * 체크카드 리스트 아답터
	 */
	private class CreditCardListAdapter extends ArrayAdapter<CreditCardData> 
	{
    	private Context context;
    	private int textViewResourceId;
    	private ArrayList<CreditCardData> items;
    	private LayoutInflater inflater;
    	
		public CreditCardListAdapter(Context context, int textViewResourceId, ArrayList<CreditCardData> items) {
			super(context, textViewResourceId, items);
			this.context = context;
			this.textViewResourceId = textViewResourceId;
			this.items = items;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View view = convertView;
			
			if (view == null) 
			{
				inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.list_item_card, null);
			}
			
			CreditCardData data = items.get(position);
			
			if (data != null) 
			{
				TextView textName = (TextView)view.findViewById(R.id.SETTING_CHECKCARD_LIST_textName);
				TextView textlink = (TextView)view.findViewById(R.id.SETTING_CHECKCARD_LIST_linkName);
				TextView textMoney = (TextView)view.findViewById(R.id.SETTING_CHECKCARD_LIST_textMoney);
				
				textName.setText(data.getName());
				textlink.setText(data.getLinkName());
				//textMoney.setText(BDUtil.getWon(data.getOutMoney()) + shape);
				textMoney.setText(BDUtil.getWon(data.getOutMoney().toString()) + shape);
			}
			
			return view;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(CreditCardActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setData();
				return 0;
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				if (mListCreditCard.getFooterViewsCount() > 0)
				{
					mListCreditCard.removeFooterView(resultView);
				}
				
				if (mArrayCreditCard.size() < 1)
				{
					mListCreditCard.addFooterView(resultView);
					mListCreditCard.setFooterDividersEnabled(false);
					mListCreditCard.setOnItemClickListener(null);
				}
				else
				{
					mListCreditCard.setOnItemClickListener(onItemClickListener);
					mListCreditCard.setFooterDividersEnabled(true);
				}
				
				mAdapterCreditCard = new CreditCardListAdapter(
						CreditCardActivity.this, R.layout.list_item_card, mArrayCreditCard);
				mListCreditCard.setAdapter(mAdapterCreditCard);
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
	
	
}
